// import { ZryDocSchema, PartialBlock, locales } from "@zry-doc/core";
import { locales, ZryDocSchema } from "@zry-doc/core";
import { useCreateZryDoc } from "@zry-doc/react";
import { ZryDocView } from "@zry-doc/shadcn";
import { useMemo } from "react";
import { WebsocketProvider } from "y-websocket";
import * as Y from "yjs";

interface DocEditorProps {
  // pageId: string;
  // initialContent?: PartialBlock[];
  doc: Y.Doc;
  provider: WebsocketProvider;
}

const schema = ZryDocSchema.create({});

// export function DocEditor(props: DocEditorProps) {
export function DocEditor(props: DocEditorProps) {
  const { doc, provider } = props;

  // const provider = new WebsocketProvider("ws://ruiyangz.top:5000", "document");

  const currentUser = {
    username: "ruiyangz",
  };

  const randomColor = useMemo(() => {
    const storedColor = sessionStorage.getItem("zrydoc-user-color");
    if (storedColor) {
      return storedColor;
    }
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    const color = `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
    sessionStorage.setItem("zrydoc-user-color", color);
    return color;
  }, []);

  const editor = useCreateZryDoc(
    {
      schema,
      dictionary: locales.zh, // 语言包
      collaboration: {
        // The Yjs Provider responsible for transporting updates:
        provider,
        // Where to store data in the Y.Doc:
        fragment: doc.getXmlFragment(`docs-1`),
        // Information (name and color) for this user:
        user: {
          name: currentUser?.username ?? "",
          color: randomColor,
        },
        // renderCursor: cursorRender,
      },
    },
    [],
  );

  return <ZryDocView editor={editor} />;
}
